package com.bidevalution.support.util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Log4j2
public class HttpClientUtil {
	private static Logger log = Logger.getLogger(HttpClientUtil.class);
	/**
     * 带参数的post请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static  String doPost(String url, Map<String, String> map) throws Exception {
        // 声明httpPost请求
         HttpPost httpPost = new HttpPost(url);
         //配置超时时间
         RequestConfig requestConfig = RequestConfig.custom().
                 setConnectTimeout(1000).setConnectionRequestTimeout(1000)
                 .setSocketTimeout(1000).setRedirectsEnabled(true).build();
         //设置超时时间
         httpPost.setConfig(requestConfig);
         httpPost.addHeader(new BasicHeader("Content­Type","application/json"));
         CloseableHttpClient httpClient = HttpClients.createDefault();
        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
 
            // 遍历map，设置参数到list中
            for (Map.Entry<String, String> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
 
            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
            formEntity.setContentType("application/json");
 
            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }
 
        // 使用HttpClient发起请求，返回response
        CloseableHttpResponse response = httpClient.execute(httpPost);
 
        // 解析response封装返回对象httpResult
        if (response.getEntity() != null) {
        	return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }
    public static String doGet(String url) {
    	CloseableHttpClient httpCilent = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)   //设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        try {
            HttpResponse httpResponse = httpCilent.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                return  EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
            
            }else{
                return null;
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }finally {
            try {
                httpCilent.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    /**
     * 根据url下载文件
     * @param url 下载地址
     * @return 返回文件流
     * @throws IOException
     */
    public static InputStream downloadFile(String url) throws IOException {
        HttpClient client = new HttpClient();
        InputStream in;
        //建立连接
        GetMethod method = new GetMethod(url);
        //执行url请求
        try {
            client.executeMethod(method);
            //获取文件
            in = method.getResponseBodyAsStream();

        } catch (Exception e) {
            method.releaseConnection();
            throw e;
        }
        return in;
    }
}
